<?php

namespace App\Http\Api\Controllers;

use App\Http\Api\Services\MiniProgrom as MiniProgromService;
use App\Services\Account as AccountService;
use Phalcon\Http\Response as HttpResponse;

/**
 * @RoutePrefix("/api/mp")
 */
class MpController extends Controller
{

    /**
     * @Get("/openid", name="api.mp.openid")
     *
     * 请求参数
     * code
     *
     */
    public function openidAction(): HttpResponse
    {
        [
            'code' => $code,

        ] = $this->request->getQuery();

        $mp = new MiniProgromService();

        $service = $mp->getMpService();

        $openid = $service->session($code);

        return $this->jsonSuccess([
            'openid' => $openid,
        ]);
    }

    /**
     * @Post("/login", name="api.mp.login")
     *
     * 请求参数
     * openid
     * rawData
     * signature
     * encryptedData
     * iv
     */
    public function loginAction(): HttpResponse
    {
        $mp = new MiniProgromService();

        $service = $mp->getMpService();

        $post = $this->request->getPost();

        $token = $service->login($post);

        $userId = $this->getAuthUser()->id;
        $accountService = new AccountService();
        $accountModel = $accountService->get($userId);

        return $this->jsonSuccess([
            'token' => $token,
            'missing_mobile' => !$accountModel->phone, // 登录成功后检查是否有手机号
        ]);
    }

    /**
     * @Post("/bind/login", name="api.mp.weixin.bind_login")
     *
     * 请求参数:
     * openid
     * rawData
     * account
     * password
     *
     */
    public function bindLoginAction(): HttpResponse
    {
        $post = $this->request->getPost();

        $mp = new MiniProgromService();

        $service = $mp->getMpService();

        $token = $service->bindLogin($post);

        return $this->jsonSuccess([
            'token' => $token,
        ]);
    }


    /**
     * @Post("/bind/register", name="api.mp.weixin.bind_register")
     *
     * 请求参数：
     * openid
     * rawData
     * account
     * password
     * verify_code
     *
     */
    public function bindRegisterAction(): HttpResponse
    {
        $post = $this->request->getPost();

        $mp = new MiniProgromService();

        $service = $mp->getMpService();

        $token = $service->bindRegister($post);

        return $this->jsonSuccess([
            'token' => $token,
        ]);
    }

    /**
     * @Post("/bind/current", name="api.mp.bind_current")
     *
     * 请求参数
     * openid
     * rawData
     *
     */
    public function bindCurrentAction(): HttpResponse
    {
        $post = $this->request->getPost();

        $mp = new MiniProgromService();

        $service = $mp->getMpService();

        $service->bindCurrent($post);

        return $this->jsonSuccess();
    }

}
